<template>
	<button class="recognizeBtn" type="primary" @click="chooseImage">
		<image mode="aspectFill" src="/static/my/camera.png"></image>
	</button>
</template>

<script>
	import {
		toBase64
	} from './common/base64.js';
	export default {
		data() {
			return {
				dataObj: {
					client_id: 'luQMtHHVwK5OuXpUonQGVUw2',
					client_secret: 'znZGkwZeKNb1Gu9M56rOdPNXmlxypgdo',
				}
			}
		},
		methods: {
			// 选择本地图片
			chooseImage() {
				const self = this;
				uni.chooseImage({
					count: 1,
					success: (res) => {
						uni.showLoading({
							title: '正在识别中...'
						})
						self.$emit('start', {
							animal: true,
							img: res.tempFilePaths[0]
						})
						// 下面将图片本地路径转base64
						toBase64(res.tempFilePaths[0]).then((res) => {
							self.getAccessToken(res)
						})
					}
				})
			},
			// 获取AccessToken
			getAccessToken(path) {
				const self = this;
				uni.request({
					url: 'https://aip.baidubce.com/oauth/2.0/token',
					data: {
						grant_type: 'client_credentials',
						client_id: self.dataObj.client_id,
						client_secret: self.dataObj.client_secret
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						self.uploadImage(path, res.data.access_token)
					}
				})
			},
			// 通用文字识别（高精度版）
			uploadImage(path, token) {
				const self = this;
				uni.request({
					// url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic',
					url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard',
					data: {
						image: path,
						access_token: token
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.hideLoading()
						self.$emit('end', {
							animal: false,
							result: res.data.result
						})
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.recognizeBtn {
		line-height: 1;
		padding: 0;
		margin: 0;
		background: #ffffff;

		>image {
			width: 45rpx;
			height: 37rpx;
		}
	}
</style>